import axios, { AxiosResponse } from 'axios'
import type { AxiosInstance, AxiosRequestConfig } from 'axios'
import { IJJRequestConfig, IJJRequestInterceptors } from './types'

class JJRequest {
  instance: AxiosInstance
  //该属性从实例中获取
  interceptors?: IJJRequestInterceptors

  constructor(config: IJJRequestConfig) {
    this.instance = axios.create(config)
    //从实例配置config中获取拦截器配置
    this.interceptors = config.interceptors
    //全局请求拦截
    this.instance.interceptors.request.use(
      (config) => {
        console.log('全局请求拦截')
        return config
      },
      (error) => {
        console.log('全局请求失败拦截', error)
      }
    )
    //全局响应拦截
    this.instance.interceptors.response.use(
      (res) => {
        //res为AxiosResponse类型，含有config\data\headers\request\status\statusText属性
        //改造返回的数据类型，即将AxiosResponse的data返回
        console.log('全局响应拦截')
        return res.data
      },
      (error) => {
        console.log('全局响应失败拦截', error)
        return error
      }
    )

    //实例级别拦截
    this.instance.interceptors.request.use(
      this.interceptors?.requestInterceptor,
      this.interceptors?.requestInterceptorCatch
    )
    this.instance.interceptors.response.use(
      this.interceptors?.responseInterceptor,
      this.interceptors?.responseInterceptorCatch
    )
  }

  get<T = any>(config: IJJRequestConfig<T>): Promise<T> {
    return this.request<T>({
      ...config,
      method: 'GET',
    })
  }
  post<T = any>(config: IJJRequestConfig<T>): Promise<T> {
    return this.request<T>({
      ...config,
      method: 'POST',
    })
  }

  request<T>(config: IJJRequestConfig<T>): Promise<T> {
    return new Promise<T>((resolve, reject) => {
      //请求拦截设置位置
      if (config.interceptors?.requestInterceptor) {
        config = config.interceptors.requestInterceptor(config)
      }

      this.instance
        .request<any, T>(config)
        .then((res) => {
          //响应拦截设置位置
          if (config.interceptors?.responseInterceptor) {
            res = config.interceptors.responseInterceptor(res)
          }
          resolve(res)
        })
        .catch((err) => {
          console.log('=====', err)
          reject(err)
        })
    })
  }
}

export { JJRequest }
